﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone;
using Microsoft.Phone.Shell;
using WP7Client.RssFeedService;

namespace WP7Client
{
    public partial class MainPage : PhoneApplicationPage
    {
        public Session _session;

        // Constructeur
        public MainPage()
        {
            InitializeComponent();
            // Debug
            passwordBox.Password = "admin";
            emailBox.Text = "admin@mail.com";
        }


        PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

        private void connectButton_Click(object sender, RoutedEventArgs e)
        {
            loader.Opacity = 1;
            RssFeedServiceClient client = new RssFeedServiceClient("BasicHttpBinding_IRssFeedService");
            client.startSessionCompleted += new EventHandler<startSessionCompletedEventArgs>(startSessionSuccess);
            String password = passwordBox.Password;
            String email = emailBox.Text;
            client.startSessionAsync(email, password, ServiceDevice.WP7);
        }

        private void startSessionSuccess(object sender, startSessionCompletedEventArgs e)
        {
            _session = e.Result;
            loader.Opacity = 0;
            if (e.Result.status == ServiceStatus.Success)
            {
                NavigationService.Navigate(new Uri("/PivotPage.xaml", UriKind.Relative));
                phoneAppService.State["session"] = e.Result;
            }
            else
                displayErrorLogin(e.Result.status);
        }

        private void displayErrorLogin(ServiceStatus status)
        {
            if (status == ServiceStatus.ServerError)
                textBlockError.Text = "Le serveur à rencontré une erreur interne !";
            else if (status == ServiceStatus.WrongParameter)
                textBlockError.Text = "Paramétres invalide !";
            else if (status == ServiceStatus.ConnectedOnAnotherDevice)
                textBlockError.Text = "Ce compte est déjà connecté via une autre plateforme.";
        }
    }
}